package com.zgis.module.db.controller;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.zgis.module.db.service.TableCacheService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 表缓存管理控制器
 */
@Tag(name = "管理后台 - 表缓存管理")
@Validated
@Slf4j
@RestController
@RequestMapping("/tool/table-cache")
public class TableCacheController {

    @Resource
    private TableCacheService tableCacheService;

    @PostMapping("/reload-all")
    @Operation(summary = "重新加载所有表缓存")
    public CommonResult<Boolean> reloadAllTables() {
        try {
            tableCacheService.reloadAllTables();
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[TableCacheController] 重新加载表缓存失败", e);
            return CommonResult.error(500, "重新加载失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/clear-all")
    @Operation(summary = "清除所有表缓存")
    public CommonResult<Boolean> clearAllCache() {
        try {
            tableCacheService.clearAllCache();
            return CommonResult.success(true);
        } catch (Exception e) {
            log.error("[TableCacheController] 清除缓存失败", e);
            return CommonResult.error(500, "清除失败: " + e.getMessage());
        }
    }

    @GetMapping("/get/{cacheKey}")
    @Operation(summary = "获取缓存数据")
    public CommonResult<List<Map<String, Object>>> getCachedData(@PathVariable String cacheKey) {
        try {
            List<Map<String, Object>> data = tableCacheService.getCachedTableData(cacheKey);
            return CommonResult.success(data);
        } catch (Exception e) {
            log.error("[TableCacheController] 获取缓存数据失败", e);
            return CommonResult.error(500, "获取失败: " + e.getMessage());
        }
    }
}
